package com.maori.languageapp.userprofile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.R;
import com.maori.languageapp.UploadToFtp;
import com.maori.languageapp.consts.ImageLoader;
import com.maori.languageapp.discover.word.Maori_Discover_Word;
import com.maori.languageapp.usermanager.Languageapp_Register_New_User;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Maori_Display_User_Profile extends Activity {
	EditText first_name, last_name, tribe, email, username, role, user_created,
			last_login, userlocation;
	TextView profile_text, profile_text_name;
	ImageView profile_image, camera_button;
	ProgressDialog mProgressDialog;
	private SQLiteDatabase mydb;
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	String CurrentUID, result, lastLoginTime;
	int timeoutConnection = 5000;
	InputStream is = null;
	StringBuilder sb = null;
	JSONArray jArray;
	HttpParams httpParameters = new BasicHttpParams();
	ArrayList<HashMap<String, String>> arraylist;
	JSONArray jsonarray;
	String print_MID, PrintMainEmail;
	Button cancelbtn, submitbtn;
	TextView screenTitle;
	Bitmap bmImg = null;
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	private Uri fileUri;
	private static final String IMAGE_DIRECTORY_NAME = "lANGUAGEAPP";
	protected static final String TAG = null;
	static String upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
	static String filename = "404";
	static String sourceUrl;
	String desDirectory = "http://langapp.testarea.co.nz:2082/lanappimage/";
	public void btnBackAction(View view) {
		Maori_Display_User_Profile.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}

	@Override
	public void onBackPressed() {
		Maori_Display_User_Profile.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// setContentView(R.layout.maori_login);
		setContentView(R.layout.maori_display_user_profile);

		camera_button = (ImageView) findViewById(R.id.takephoto);
		profile_image = (ImageView) findViewById(R.id.profile_image);
		first_name = (EditText) findViewById(R.id.first_name);
		last_name = (EditText) findViewById(R.id.last_name);
		tribe = (EditText) findViewById(R.id.tribe);
		email = (EditText) findViewById(R.id.email);
		username = (EditText) findViewById(R.id.username);
		role = (EditText) findViewById(R.id.role);
		user_created = (EditText) findViewById(R.id.user_created);
		last_login = (EditText) findViewById(R.id.last_login);
		userlocation = (EditText) findViewById(R.id.userlocation);

		profile_text = (TextView) findViewById(R.id.profile_text);
		profile_text_name = (TextView) findViewById(R.id.profile_text_name);
		screenTitle = (TextView) findViewById(R.id.screenTitle);
		
		cancelbtn = (Button) findViewById(R.id.cancelbtn);
		submitbtn = (Button) findViewById(R.id.submitbtn);

		cancelbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				onBackPressed();
			}
		});

		submitbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				new UploadTask().execute();
			}
		});
		
		screenTitle.setText("My Profile");

		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterUserInfo = new ContentValues();
		Cursor readUserDetails = null;
		try {
			String queryCheckUsers = "SELECT * FROM User Where Activate = '1'";
			readUserDetails = mydb.rawQuery(queryCheckUsers, null);
		} catch (Exception e) {

		}
		if (readUserDetails != null) {
			if (readUserDetails.getCount() > 0) {
				while (readUserDetails.moveToNext()) {
					CurrentUID = readUserDetails.getString(11);
					lastLoginTime = readUserDetails.getString(9);
				}
			} else {
				CurrentUID = "1";
			}
		}
		mydb.close();

		new DownloadUserData().execute();

		camera_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				first_name.setEnabled(true);
				last_name.setEnabled(true);
				tribe.setEnabled(true);
				email.setEnabled(true);
				username.setEnabled(true);
				role.setEnabled(true);
				user_created.setEnabled(true);
				last_login.setEnabled(true);
				userlocation.setEnabled(true);
				
				
				
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
						ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				Log.v(TAG, "PRINT _ 1: " + fileUri);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
				// start the image capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
			}
		});
	}

	private class DownloadUserData extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Display_User_Profile.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Loading");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading User Details..");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/getUserProfileData.php");
				JSONObject json = new JSONObject();
				json.put("record1", CurrentUID);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "View User Data**** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();

				}
			} catch (Exception e) {

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			if (result != null) {
				arraylist = new ArrayList<HashMap<String, String>>();
				try {
					JSONObject jsonObj = new JSONObject(result);
					jsonarray = jsonObj.getJSONArray("posts");
					for (int i = 0; i < jsonarray.length(); i++) {
						JSONObject c = jsonarray.getJSONObject(i);
						String print_first_name = c.getString("first_name");
						String print_last_name = c.getString("last_name");
						String print_tribe = c.getString("tribe");
						PrintMainEmail = c.getString("email");
						String print_username = c.getString("username");
						String print_role = c.getString("role");
						String print_user_created = c.getString("user_created");
						String print_last_logedIn = c.getString("last_logedIn");
						String print_status = c.getString("status");
						print_MID = c.getString("MID");
						String print_current_location = c
								.getString("current_location");
						String print_UID = c.getString("UID");

						first_name.setText(print_first_name);
						last_name.setText(print_last_name);
						tribe.setText(print_tribe);
						email.setText(PrintMainEmail);
						username.setText(print_username);
						role.setText(print_role);
						user_created.setText(print_user_created);
						last_login.setText(lastLoginTime);
						userlocation.setText(print_current_location);

						profile_text.setText(PrintMainEmail);
						profile_text_name.setText(print_first_name + " "
								+ print_last_name);
						
						Log.e("DDDDD", "XXXX  : " + print_MID);
						
						try {
							ImageLoader imgLoader = new ImageLoader(getApplicationContext());
							imgLoader.DisplayImage(print_MID, profile_image);
							
						} catch (Exception e) {
							Log.e("TAG ", "Exception : " + e);
						}
						profile_image.setImageBitmap(bmImg);
						// Create an object for subclass of AsyncTask
						//GetXMLTask task = new GetXMLTask();
						// Execute the task
						//task.execute(new String[] { print_MID });
					}
				} catch (Exception e) {

				}
			}
			mProgressDialog.dismiss();
		}
	}

	private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... urls) {
			Bitmap map = null;
			for (String url : urls) {
				map = downloadImage(url);
			}
			return map;
		}

		// Sets the Bitmap returned by doInBackground
		@Override
		protected void onPostExecute(Bitmap result) {
			profile_image.setImageBitmap(result);
		}

		// Creates Bitmap from InputStream and returns it
		private Bitmap downloadImage(String url) {
			Bitmap bitmap = null;
			InputStream stream = null;
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 1;

			try {
				stream = getHttpConnection(url);
				bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
				stream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return bitmap;
		}

		// Makes HttpURLConnection and returns InputStream
		private InputStream getHttpConnection(String urlString)
				throws IOException {
			InputStream stream = null;
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();

			try {
				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();

				if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					stream = httpConnection.getInputStream();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return stream;
		}
	}

	// ***********Camera Image Handling************************
	/*
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);
		Log.v(TAG, "PRINT _ 4: " + mediaStorageDir);
		upladingFromPath = mediaStorageDir.getAbsolutePath();
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			filename = "IMG_" + timeStamp + ".jpg";
			sourceUrl = mediaFile.toString();
			Log.v(TAG, "PRINT _ 5: " + filename);
			Log.v(TAG, "PRINT _ 6: " + sourceUrl);

		} else {
			return null;
		}

		return mediaFile;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			// hide video preview
			// videoPreview.setVisibility(View.GONE);
			profile_image.setVisibility(View.VISIBLE);
			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();
			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;
			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);
			profile_image.setImageBitmap(bitmap);
			Log.v(TAG, "PRINT _ PREVIEW 1 : " + fileUri.getPath());

		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}
	
	
	class UploadTask extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(
					Maori_Display_User_Profile.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Updating");
			// Set progressdialog message
			mProgressDialog.setMessage("Update User Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
			/*pDialog = new ProgressDialog(Languageapp_Register_New_User.this);
			pDialog.setMessage("Uploading Image Files...");
			pDialog.show();*/
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + filename);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtp().ftpUpload1(upladingFromPath,
					filename, desDirectory);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (uploadStat) {

					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								Maori_Display_User_Profile.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);
			new UploadingWordsDetails().execute();

		}
	}

	
	
	private class UploadingWordsDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
		}
		//usermanager
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/usermanager/updateuseruser.php");
				
				JSONObject json = new JSONObject();
				// etfirst_name,etlast_name,ettribe,etemail,etusername,etpassword,etpasswordconfirm,etrole;
				json.put("record1", first_name.getText().toString());
				json.put("record2", last_name.getText().toString());
				json.put("record3", tribe.getText().toString());
				json.put("record4", email.getText().toString());
				json.put("record5", username.getText().toString());
				json.put("record6", role.getText().toString());
				json.put("record7", user_created.getText().toString());
				json.put("record8", last_login.getText().toString());
				json.put("record9", userlocation.getText().toString());
				json.put("record10", PrintMainEmail);
				json.put("record11", "http://langapp.mirzabros.com/lanappimage/" + filename);
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					
				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			final AlertDialog alertDialog = new AlertDialog.Builder(
					Maori_Display_User_Profile.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPDATE SUCCESS");
			// Setting Dialog Message
			alertDialog.setMessage("User Details Upload Successfully");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					onBackPressed();
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
			
		}
	}
}
